<?php

namespace app\admin\controller\wwh;

use app\common\controller\Backend;
use fast\Tree;

class Archives extends Base
{
    protected $model = null;
    protected $searchFields = 'title';
    protected $multiFields = ['weigh'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wwh\Archives;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("recDataList", $this->model->getRecDataList());
        $this->view->assign("langList", $this->model->getLangList());
        $this->view->assign("dTypeList", $this->model->getdTypeList());
    }

    /**
     * 动态获取栏目列表
     */
    public function getColumnList()
    {
        $lang = $this->request->get('lang', 1);
        $all = collection(model('\app\admin\model\wwh\Column')->where('lang', $lang)->order('weigh desc,id desc')->select())->toArray();
        $columnList = [];
        foreach ($all as $v) {
            $state = ['opened' => true];
            if (in_array($v['classify'], ['none', 'link', 'service', 'partner', 'about'])) {
                $state['disabled'] = true;
            }
            $columnList[] = [
                'id' => $v['id'],
                'parent' => $v['parent_id'] ? $v['parent_id'] : '#',
                'text' => $v['name'],
                'type' => $v['type'],
                'state' => $state
            ];
        }
        return json(['code' => 1, 'data' => $columnList]);
    }

    /**
     * 生成栏目下拉选项
     */
    protected function buildColumnOptions($lang, $selectedId = null, $restrictClassify = null)
    {
        $all = collection(model('\app\admin\model\wwh\Column')
            ->where('lang', $lang)
            ->order('weigh desc,id desc')
            ->select())->toArray();

        $tree = Tree::instance()->init($all, 'parent_id');
        $treeList = $tree->getTreeList($tree->getTreeArray(0), 'name');

        $columnOptions = '';
        foreach ($treeList as $v) {
            // 基础禁用规则
            $isDisabled = in_array($v['classify'], ['none', 'link', 'service', 'partner', 'about']);

            if ($restrictClassify !== null && $v['classify'] !== $restrictClassify) {
                $isDisabled = true;
            }

            // 组合成 disabled 字符串
            $disabled = $isDisabled ? ' disabled' : '';

            // 确保当前选中的栏目不会被禁用
            if ($selectedId !== null && $v['id'] == $selectedId) {
                $disabled = '';
            }

            $selected = ($selectedId !== null && $v['id'] == $selectedId) ? ' selected' : '';
            $spacer = str_repeat('&nbsp;&nbsp;', $v['level'] ?? 0);
            $columnOptions .= "<option value='{$v['id']}'{$selected}{$disabled}>{$spacer}{$v['name']}</option>";
        }

        return $columnOptions;
    }

    /**
     * 查看
     */
    public function index()
    {
        $this->relationSearch = true;
        $this->request->filter(['strip_tags', 'trim']);

        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['column'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                parent::add();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $lang = $this->request->get('lang', 1);
        $this->view->assign('columnOptions', $this->buildColumnOptions($lang));
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        // 获取当前文章所属栏目的 `classify`
        $currentColumn = \app\admin\model\wwh\Column::get($row['column_id']);
        $restrictClassify = $currentColumn ? $currentColumn->classify : null;

        // 调用 buildColumnOptions 时传入 restrictClassify
        $lang = $row['lang'];
        $this->view->assign('columnOptions', $this->buildColumnOptions($lang, $row['column_id'], $restrictClassify));

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                parent::edit($ids);
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 审核
     */
    public function audit($ids)
    {
        foreach ($ids as $k => $v) {
            $res = $this->model->where(['id' => ['in', $ids]])->update(['status' => 1]);
            if ($res == true) {
                $this->success('审核成功');
            } else {
                $this->error('未更新任何行');
            }
        }
    }

    /**
     * 反审核
     */
    public function faudit($ids)
    {
        $res = $this->model->where(['status' => '1', 'id' => $ids])->update(['status' => 0]);
        if ($res) {
            $this->success('反审核成功');
        } else {
            $this->error('未更新任何行');
        }
    }
}
